package android.bbs.notice;


import java.io.BufferedReader;
import java.io.InputStreamReader;

import org.apache.http.HttpResponse;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.bbs.Bbs;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.utility.Utility;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
import android.widget.Toast;

import com.example.piano_application.R;

/**
 * 공지사항 자세히 보기
 * */
public class Notice_read extends Activity implements OnClickListener{
	ProcessGet processGet;
	
	private int notice_no;
	
	private String title;
	private String name;
	private String contents;
	private String date;
	private String file;
	
	
	private TextView txv_name;
	private TextView txv_title;
	private TextView txv_date;
	private TextView txv_contents;
	private TextView txv_file;
	private TextView txv_update;
	private TextView txv_delete;
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.notice_read);
        
        Intent intent = getIntent();
        notice_no = intent.getIntExtra("noticeno", 0);
        
        txv_update = (TextView)findViewById(R.id.txv_notice_update);
        txv_update.setOnClickListener(this);
        
        txv_delete = (TextView)findViewById(R.id.txv_notice_delete);
        txv_delete.setOnClickListener(this);
        
        txv_name = (TextView)findViewById(R.id.txv_notice_read_name);
        
        txv_title = (TextView)findViewById(R.id.txv_notice_read_title);
        
        txv_date = (TextView)findViewById(R.id.txv_notice_read_date);
        
        txv_contents = (TextView)findViewById(R.id.txv_notice_read_contents);
        
        txv_file = (TextView)findViewById(R.id.txv_notice_read_file);
        
        noticeRead();
        
	}
	
	public void noticeRead(){
		 StringBuilder html = new StringBuilder();
	        try {
	            BufferedReader br = Utility.loadHTML(NoticeConst.READ+ "?noticeno="+ notice_no);
	            
	                while (true) {
	                    String line = br.readLine();
	                    if (line == null) break;
	                    html.append(line + '\n'); 
	                    
	                }
	                
	                br.close();
	                

	                JSONObject memberobj = new JSONObject(html.toString());
	                JSONArray memberja = memberobj.getJSONArray("data");
	                
	                for (int i = 0; i < memberja.length(); i++) {
	                	JSONObject item = memberja.getJSONObject(i);
	                
	                	name = item.getString("nickname");
	                	txv_name.setText(name);
	                
	                	title = item.getString("title");
	                	txv_title.setText(title);
	                	
	                	contents = item.getString("contents");
	                	txv_contents.setText(contents);
	                
	                	date = item.getString("noticedate").substring(5, 10);
	                	txv_date.setText(date);
	                	
	                	file = item.getString("profilephoto");
	                	txv_file.setText(file);
	                
	                }
	                
//	                JSONObject bbsobj = new JSONObject(html.toString());
//	                title = bbsobj.getString("title").toString();
//	                contents = bbsobj.getString("contents").toString();
//	                name = bbsobj.getString("nname").toString();
//	                date = (bbsobj.getString("date").substring(5, 10)).toString();;
//	                file = bbsobj.getString("filephoto").toString();
//	               
//	                txv_name.setText(name);
//	                txv_title.setText(title);
//	                txv_date.setText(date); 
//	                txv_contents.setText(contents);
//	                txv_file.setText(file);
	                
//	                profilephoto = BbsConst.PROFILEPATH + bbsprofilephoto; 
//	                webfilename = BbsConst.PICTURIPath + bbsfilename; 
//	               
//	                downloadFile(webfilename); // 해당파일을 다운로드 합니다. 
//	                downloadProfile(profilephoto);
	                
	             } catch (Exception e) {
	                 Log.d("D", e.toString());
	             }
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		if (v.getId() == R.id.txv_notice_update) {
			Intent intent = null;
			intent = new Intent(getApplicationContext(), Notice_update.class);
			intent.putExtra("noticeno", notice_no);
			intent.putExtra("name", name);
			intent.putExtra("contents", contents);
			intent.putExtra("title", title);
			intent.putExtra("profilephoto", file);
			startActivity(intent);
        } else if(v.getId() == R.id.txv_notice_delete) {
        	Toast.makeText(this, "공지사항을 삭제합니다.", Toast.LENGTH_SHORT).show();
        	dialog();
        }
	}
	
	public void dialog(){
		AlertDialog dialog = createDialogBox();
		dialog.show();
	}
	
	private AlertDialog createDialogBox(){
		
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		
		builder.setTitle("안내");
		builder.setMessage("공지사항을 삭제합니다.");
		
		builder.setPositiveButton("확인", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				 String addr = NoticeConst.DELETE + "?noticeno=" + notice_no;
				 processGet = new ProcessGet(addr);
                 processGet.start();
			}
		})
		.setNegativeButton("취소", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
                String str = "취소 했습니다.";
                Toast.makeText(Notice_read.this, str, Toast.LENGTH_LONG).show();
            }
        });
		
		AlertDialog dialog = builder.create();
		return dialog;
	}
	
	class ProcessGet extends Thread{
        String _addr;

        ProcessGet(String addr) {
            _addr = addr;
        }

        public void run() {

            HttpGet get = new HttpGet(_addr);
            DefaultHttpClient client = new DefaultHttpClient();
            try {
                client.execute(get, responseHandler);
            } 
            catch (Exception e) {;}
        }        
    }
    
    ResponseHandler<String> responseHandler = new ResponseHandler<String>() {
        public String handleResponse(HttpResponse response) {
 
            StringBuilder html = new StringBuilder(); 
            String message = "";
            try {                
                BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
                while (true) {
                    String line = br.readLine();
                    if (line == null) break;
                    html.append(line + '\n'); 
                }
                br.close();

                JSONObject obj = new JSONObject(html.toString());
                
                String code = obj.getString("code");
                message = obj.getString("message");
                
                if (code.equals("success")){
                    Message msg = msgHandler.obtainMessage();
                    msg.what = 1;
                    msg.obj = message;
                    msgHandler.sendMessage(msg);   
                } else if (code.equals("fail")){
                    Message msg = msgHandler.obtainMessage();
                    msg.what = 2;
                    msg.obj = message;
                    msgHandler.sendMessage(msg);   
                } else if ( code.equals("error")){
                	Message msg = msgHandler.obtainMessage();
                    msg.what = 3;
                    msg.obj = message;
                    msgHandler.sendMessage(msg);   
                }
            } catch (Exception e) {
                Message msg = msgHandler.obtainMessage();
                msg.what = 4;
                msg.obj = message;
                msgHandler.sendMessage(msg);
            }
            return html.toString();
        }
    };
	
    @SuppressLint("HandlerLeak")
	Handler msgHandler = new Handler() {
        public void handleMessage(Message msg) {
            Log.d("D", "handleMessage Call");
            // Log.d("D", "msg.what: " + msg.what);
            
            if (msg.what == 1){
                setResult(RESULT_OK, (new Intent()).setAction("SUCCESS")); // "SUCCESS"를 넘겨준다.
                // 종료 
                Intent intent = null;
    			intent = new Intent(getApplicationContext(), Bbs.class);
    			startActivity(intent);
    			finish();
            }else if (msg.what == 2){
                
            }else if (msg.what == 3){
                
            }else if (msg.what == 4){
            }            
        }
    };
	
    
    /** 뒤로가기 */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
        	Intent intent = null;
			intent = new Intent(getApplicationContext(), Bbs.class);
			startActivity(intent);
			finish();
        } 
        return false;
    }

   
		
}
